/* $RCSFile: CrmRating.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/CrmRating/CrmRating.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:20  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:51  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Linq;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Settings;
using AddonNice.Helpers;
using AddonNice.Diagnostics;
using AddonNice.Configuration.Settings;
using AddonNice.Settings.PageModules.CrmRating;
using AddonNice.Core;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.CrmRating;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using AddonNice.Authentication;

namespace AddonNice.PageModules.CrmRating
{

    /// <summary>
    /// Initializer for CrmRating 
    /// </summary>
    public class CrmRatingSI : CrmRatingBaseSI
    {
        public CrmRatingSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( RatingTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmRatingSI Ctor BEG.",RatingTrace.Sw.Info);
            InitSettings(bSettings,pm);
            if ( RatingTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmRatingSI Ctor END.",RatingTrace.Sw.Info);
        }

        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( RatingTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmRatingSI InitSettings BEG.",RatingTrace.Sw.Info);
            base.InitSettings(bSettings,pm);


            if ( RatingTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmRatingInitializer Ctor END.",RatingTrace.Sw.Info);
        }
    }

    /// <summary>
    /// Input Rating about an Item
    /// </summary>
    public partial class CrmRating : PortalCRMModuleControl 
    {
		RatingDB CrmRatingDB        =   new RatingDB();
        RatingContext _RContext     =   null;
        
        protected RatingContext RContext
        {
            get
            {
                if ( _RContext == null )
                {
                    _RContext       =   new RatingContext(Request,Wrapper,Settings,ResetWrapper);
                    if ( IsTrackingViewState )
                        ( (IStateManager)_RContext ).TrackViewState();
                }
                return _RContext;
            }
        }

		#region General Implementation

        public override bool NeedAttachedEntity
        {
            get
            {
                return false;
            }
        }

		public override Guid GuidID 
		{
			get
			{
				return new Guid("{893D0AF4-A50B-4657-8F28-456790B475F3}");
			}
		}

        public override bool DependsFromCustomCrmEntities
        {
            get{ return true;}
        }

        /// <summary>
        /// SortedList of entities/version from which this module depends, schema name is the key, version is a string in the form major.minor
        /// </summary>
        public override SortedList<string,string> RelatedCustomEntities
        {
            get
            {
                SortedList<string,string> Lst =   new SortedList<string,string>();
                Lst.Add(CrmStr.rating,"1.0");
                Lst.Add(CrmStr.ratingdetail,"1.0");
                Lst.Add(CrmStr.ratinganswer,"1.0");
                return Lst;
            }
        }

		#endregion

        /// <summary>
        /// Public constructor. Sets base settings for module.
        /// </summary>
        public CrmRating() 
        {
            if ( RatingTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmRating Ctor END.",RatingTrace.Sw.Info);
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                     =   "CRMRATING";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new CrmRatingSI(bSettings,this);
        }


        /// <summary>
        /// The Page_Load event handler on this User Control is used to
        /// obtain a DataSet of announcement information from the CrmRating
        /// table, and then databind the results to a templated DataList
        /// server control.  It uses the AddonNice.CrmRatingDB()
        /// data component to encapsulate all data functionality. 
        /// </summary>
        protected void Page_Load(object sender, System.EventArgs e) 
        {
			if (RatingTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmRating Page_Load Time: {0}, IsPostBack: {1}",DateTime.UtcNow,IsPostBack),RatingTrace.Sw.Info);
            if ( !IsPostBack )
            {
                // If custom rating entities required and not installed in CRM , display message
                if ( RContext.UseCrm && !RContext.IsCutomInstalled )
                {
			        if (RatingTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( "[V]CrmRating Page_Load adn_rating not installed.",RatingTrace.Sw.Info);
                    lblRating.Text      =   LocalizeHelper.Localize("CRMRATING_NOTINSTALLED","Custom entity rating not installed");
                    RadRating1.Enabled  =   false;
                    return;
                }
                ConfigureRating();		
            }
			if (RatingTrace.Sw.TraceVerbose)
                Trace2.WriteLine("CrmRating Page_Load END.",RatingTrace.Sw.Info);
        }


        protected void ConfigureRating()
        {
            RadRating1.SelectionMode        =   (RatingSelectionMode)Enum.Parse(typeof(RatingSelectionMode),Settings[RStr.SelectionMode].Value);
            RadRating1.IsDirectionReversed  =   Settings[RStr.IsDirectionReversed].ToBool();
            RadRating1.Precision            =   (RatingPrecision)Enum.Parse(typeof(RatingPrecision),Settings[RStr.Precision].Value);
            RadRating1.Orientation          =   (Orientation)Enum.Parse(typeof(Orientation),Settings[RStr.Orientation].Value);
            bool UseFullInfo                =   Settings[RStr.UseFullInfo].ToBool();
            if ( !UseFullInfo )
            {
                pnlExtended.Visible         =   false;
            }

            if ( !RContext.ShowDescCol )
            {
                lblComments.Visible             =   false;
            }
            if ( !RContext.CurrentUser.IsAnonymous && RContext.InputComment )
            {
                pnlUserName.Visible             =   false;
            }


			SqlDataReader dr                    =   null;
		    RContext.RatingEntityName           =   string.Empty;
			try
			{
				dr                              =   CrmRatingDB.GetRatingGlobalized(ModuleID);

				// Load first row into DataReader
				if (dr.Read())
				{
					RContext.TitleRating        =   (string)dr["Title"];
                    RContext.StarNumber         =   (int)dr["StarNumber"];
                    RContext.ItemCount          =   (int)dr["ItemCount"];
					RContext.RatingEntityName   =   (string)dr["CrmEntityName"];
                    RContext.RatingExist        =   true;
				}
                // keep it after reading db
                RadRating1.ItemCount            =   RContext.StarNumber;
			}
			catch (Exception ex)
			{
				if (RatingTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmRating ConfigureRating ex: {0}", ex),RatingTrace.Sw.Info);
				throw;
			}
			finally
			{
				if (dr != null)
					dr.Close();
			}
			DataTable tb                    =   null;
			try
			{
				tb                          =   CrmRatingDB.GetRatingDetailsGlobalized(ModuleID);

				// Load first row into DataReader
				foreach(DataRow rw in tb.Rows)
				{
                    RContext.RatingItemID           =   (int)rw["ItemID"];
                    object ob                       =   rw["CrmID"];
                    if ( ob != null && !(ob is DBNull ))
                        RContext.RatingCrmDetailID  =   (Guid)ob;
                    ob                      =   rw["CrmEntityID"];
                    if ( ob != null && !(ob is DBNull ))
                        RContext.RatingCrmEntityID  =   (Guid)ob;
					RContext.TitleRatingDetail      =   (string)rw["Title"];
                    RContext.AverageRating          =   Math.Round((double)rw["AverageRating"],1);
                    lblRating.Text                  =   RContext.AverageRating.ToString();
		            if (RatingTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmRating ConfigureRating lblRating.Text: {0}, RContext.AverageRating: {1}.",
                            lblRating.Text,RContext.AverageRating),RatingTrace.Sw.Info);
                    RContext.TimesRated             =   (int)rw["TimesRated"];
					LtContent2Quote.Text            =   (string)rw["Description"];
                    string path                     =   Config.ModulesPath + "/CrmRating/CrmRatingEdit.aspx";
                    EditUrl                         =   HttpUrlBuilder.BuildUrlWithCustomAttributes(path,PageID,string.Format("mID={0}&itemid={1}", ModuleID,RContext.RatingItemID));
                    break; // TBD change for another rating format when more than one
				}
		        if (RatingTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmRating ConfigureRating RatingItemID: {0}, ShowDescCol: {1}.",RContext.RatingItemID,RContext.ShowDescCol),RatingTrace.Sw.Info);
                // Read the last non empty comments
                if ( RContext.RatingItemID != 0 )
                {
                    DataTable atb           =   CrmRatingDB.GetRatingAnswersByRatingItem(RContext.RatingItemID);
                    /*
                         @ItemID         int,
                        @RatingItemID   int,
                        @RatingValue	[float],	
                        @UserName		[nvarchar] (100), 
                        @UserId			uniqueidentifier,
                        @EMail			[nvarchar] (100),
                        @Phone			[nvarchar] (100),
                        @Address		[nvarchar] (250),
                        @City			[nvarchar] (100),
                        @Zip			[nvarchar] (50),
                        @Country		[nvarchar] (100),
                        @Comments		[nvarchar] (1000)
                     */
                    if ( RContext.ShowDescCol )
                    {
                        string fmt              =   LocalizeHelper.Localize("CRMRATING_FROM","{0} From: <strong>{1}</strong> <p>{2}</p><br/>");
			            if (RatingTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmRating ConfigureRating answer Count: {0}.",atb.Rows.Count),RatingTrace.Sw.Info);
                        var lastComments        =   atb.AsEnumerable()
                                                       .Where ( (a,i) => (a.Field<string>("Comments") != string.Empty) && i < 3)
                                                       .OrderByDescending( a=> a.Field<DateTime>("CreatedDate"));
			            if (RatingTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmRating ConfigureRating lastComments Count: {0}.",lastComments.Count()),RatingTrace.Sw.Info);
                        StringBuilder sb        =   new StringBuilder();
                        foreach ( var a in lastComments )
                        {
                            sb.AppendFormat(fmt,string.Empty,a.Field<string>("UserName"),a.Field<string>("Comments"));
                        }
                        lblComments.Text        =   sb.ToString();
                        lblComments.ForeColor   =   Color.Black;
			            if (RatingTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmRating ConfigureRating lblComments.Text: '{0}'.",lblComments.Text),RatingTrace.Sw.Info);
                    }
                }
			}
			catch (Exception ex)
			{
				if (RatingTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmRating ConfigureRating ex: {0}", ex),RatingTrace.Sw.Info);
				throw;
			}
        }

        protected void btnPostComment_Click(object sender, EventArgs e)
        {
			if (RatingTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmRating btnPostComment_Click BEG RatingAnswerID: {0}.",RContext.RatingAnswerID),RatingTrace.Sw.Info);
            string UserName             =   (TbLastName.Text == String.Empty) ? "Anonymous" : TbLastName.Text;
            if ( !RContext.CurrentUser.IsAnonymous )
            {
                UserName             =   RContext.CurrentUser.UserName;
            }
            if (!string.IsNullOrEmpty(TbComments.Text) &&  RContext.ShowDescCol )
            {
                string fmt              =   LocalizeHelper.Localize("CRMRATING_FROM","{0} From: <strong>{1}</strong> <p>{2}</p><br/>");
                lblComments.Text        =   string.Format(fmt,lblComments.Text,UserName,TbComments.Text);
                lblComments.ForeColor   =   Color.Black;
            }

			//commit changes to the DB
            Guid UserId                 =   Guid.Empty;
            string EMail                =   TbMail.Text.ToString().Trim();
            string Phone                =   TbPhone.Text.ToString().Trim();
            string Address              =   TbAddress.Text.ToString().Trim();
            string City                 =   TbCity.Text.ToString().Trim();
            string Zip                  =   TbZip.Text.ToString().Trim();
            string Country              =   TbCountry.Text.ToString().Trim();
            string Comments             =   TbComments.Text.ToString().Trim();
            if ( !RContext.CurrentUser.IsAnonymous )
            {
                AddonNiceUser CurrentUser   =   RContext.CurrentUser;
                UserName                =   CurrentUser.UserName;
                UserId                  =   CurrentUser.ProviderUserKey;
                EMail                   =   CurrentUser.Email;
                Phone                   =   CurrentUser.BillPhone;
                Address                 =   string.Format("{0} / {1} / {2}",CurrentUser.BillAddress1,CurrentUser.BillAddress2,CurrentUser.BillAddress3);
                City                    =   CurrentUser.BillCity;
                Zip                     =   CurrentUser.BillZip;
                Country                 =   CurrentUser.BillCountry;
                Comments                =   TbComments.Text.ToString().Trim();
            }

            RContext.CompleteRating(RadRating1,UserName,UserId,EMail,Phone,Address,City,Zip,Country,Comments,UserLogged);

            //Close tooltip
            string str                  =   "CloseToolTip1();";
            ScriptManager.RegisterClientScriptBlock(this.Page,typeof(Page),"closeTooltip",str,true);
			if (RatingTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmRating btnPostComment_Click END.",RatingTrace.Sw.Info);
        }
    
        protected void RadRating1_Rate(object sender, EventArgs e)
        {
			if (RatingTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmRating RadRating1_Rate BEG.",RatingTrace.Sw.Info);
			decimal ratedAverageValue   =   RContext.Rate(RadRating1,UserLogged);
            lblRating.Text              =   ratedAverageValue.ToString();
			if (RatingTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmRating RadRating1_Rate END.",RatingTrace.Sw.Info);
        }

        #region IStateManager

        /// <summary>
        /// This member overrides Control.LoadViewState
        /// </summary>
		protected override void LoadViewState(object savedState) 
		{
            if ( RatingTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmRating LoadViewState BEG.",RatingTrace.Sw.Info);
			// Customize state management to handle saving state of contained objects.
			if (savedState != null) 
			{
				object[] myState    =   (object[])savedState;

				if (myState[0] != null)
					base.LoadViewState(myState[0]);
				if (myState[1] != null)
					((IStateManager)RContext).LoadViewState(myState[1]);
			}
            if ( RatingTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmRating LoadViewState END.",RatingTrace.Sw.Info);
		}
        
        /// <summary>
        /// This member overrides Control.SaveViewState
        /// </summary>
		protected override object SaveViewState() 
		{
            if ( RatingTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmRating SaveViewState BEG.",RatingTrace.Sw.Info);
			// Customized state management to handle saving state of contained objects  such as styles.
			object baseState                =   base.SaveViewState();
			object RatingTableStyleState    =   (_RContext != null) ? ((IStateManager)_RContext).SaveViewState() : null;

			object[] myState                =   new object[2];
			myState[0]                      =   baseState;
			myState[1]                      =   RatingTableStyleState;
            if ( RatingTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmRating SaveViewState END.",RatingTrace.Sw.Info);
			return myState;
		}

        /// <summary>
        /// This member overrides Control.TrackViewState.
        /// </summary>
		protected override void TrackViewState() 
		{
            if ( RatingTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmRating TrackViewState BEG.",RatingTrace.Sw.Info);
			// Customized state management to handle saving state of contained objects such as styles.
			base.TrackViewState();
			if (_RContext!= null)
				((IStateManager)_RContext).TrackViewState();
            if ( RatingTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmRating TrackViewState END.",RatingTrace.Sw.Info);
		}

        #endregion IStateManager 
        
        #region Std Overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
			if (RatingTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmRating Page_PreInit BEG.",(RatingTrace.Sw.TraceVerbose) ? RatingTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            AddText                         =   "CRMRATING_ADD";
            AddUrl                          =   Config.ModulesPath + "/CrmRating/CrmRatingEdit.aspx";
            EditText                        =   "CRMRATING_EDIT";
            EditUrl                         =   Config.ModulesPath + "/CrmRating/CrmRatingEdit.aspx";
            base.Page_PreInit(sender, e);
			if (RatingTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmRating Page_PreInit END.",(RatingTrace.Sw.TraceVerbose) ? RatingTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }
        
        override protected void OnInit(EventArgs e)
		{
			if (RatingTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmRating OnInit BEG IsAnonymous: {0}.",RContext.CurrentUser.IsAnonymous),(RatingTrace.Sw.TraceVerbose) ? RatingTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            if ( RContext.CurrentUser.IsAnonymous )
            {
                if ( Settings[RStr.AllowAnonymous].ToBool() )
                    RadRating1.OnClientRated    =   "OnClientRated";
                else
                    RadRating1.OnClientRating   =   "OnClientRating";
            }
            else if ( RContext.InputComment )
            {
			        if (RatingTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine("[V]CrmRating OnInit InputComment.",(RatingTrace.Sw.TraceVerbose) ? RatingTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                    RadRating1.OnClientRated    =   "OnClientRated";
            }
			InitializeComponent();
			base.OnInit(e);
			if (RatingTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmRating OnInit END.",(RatingTrace.Sw.TraceVerbose) ? RatingTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
		}

        private void InitializeComponent() 
        {
			Load                                +=      new EventHandler(Page_Load);
            RadRating1.Rate                     +=      new EventHandler(RadRating1_Rate);
            btnPostComment.Click                +=      new EventHandler(btnPostComment_Click);
		}

		#endregion
    }
}

